<template>
  <view class="blog-wrapper">
    <view>
      <view class="top">
        <view  @tap.stop="toUserInfo"  class="top-left">
          <u-avatar class="avatar" :src="post.authorUrl">
          </u-avatar>
          <view class="nick-name">
            {{ checkParam(post.authorName) }}

            <view style="display: flex;align-items: center">
              <text>{{ post.publishTime }}</text>
              <text>&nbsp;{{ post.location }}</text>
            </view>
          </view>
        </view>
        <view @tap.stop="followUser()" v-if="!post?.isFollowed && post?.authorId != myUserId" class="custom-style">+&nbsp;关注</view>
        <view @tap.stop="followUser()" v-if="post?.isFollowed && post?.authorId != myUserId" class="custom-style-followed">已关注</view>
      </view>
      <view class="content">
          <u-read-more
              openText="收起" toggle color="#a1a4a6" textIndent="0"
              :color="'#000'"
              closeText="展开" :shadowStyle="shadowStyle"
              showHeight="80" ref="uReadMore">
            <rich-text style="color:#000;" :nodes="checkParam(post.title,$event)"></rich-text>
<!--            <u-parse :tag-style="tagStyle" :content="checkParam(post.title)" @load="load"></u-parse>-->
          </u-read-more>
          <u-grid :border="false">
            <u-grid-item v-for="(item,index) in fileList"
                         :key="index"
                         @click="sendFileList(index)">
              <navigator url="/pages/index/fullScreen" animation-type="">

                <image v-if="isImageUrl(item)"
                       class="file-item-multi"
                       lazy-load
                       mode="aspectFill"
                       :src="item">
                  <template v-slot:loading>
                    <up-loading-icon></up-loading-icon>
                  </template>
                  <template #error>
                    <view style="font-size: 24rpx;">加载失败</view>
                  </template>
                </image>
                <video v-if="isVideoUrl(item)"
                       object-fit="cover"
                       style="position: relative;"
                       :enable-progress-gesture="false"
                       :vslide-gesture-in-fullscreen="false"
                       :show-fullscreen-btn="false"
                       :show-center-play-btn="false"
                       :show-play-btn="false"
                       class="file-item-multi" :src="item">
                  <cover-image
                      class="play-btn"
                      src="https://www.douluodalu.icu:9000/school/static/play_white.png">
                  </cover-image>
                </video>
              </navigator>

            </u-grid-item>
          </u-grid>
        <view class="btn-wrapper">
          <view style="display: flex;align-items: center">
            <image  class="btn-img" src="https://www.douluodalu.icu:9000/school/static/share.png"></image>
            &nbsp;<text>&nbsp;分享</text>
          </view>
          <view style="display: flex;align-items: center">
            <image class="btn-img" src="https://www.douluodalu.icu:9000/school/static/comment.png"></image>
            <text >&nbsp;{{checkParam(post.comment)}}</text>
          </view>
          <view style="display: flex;align-items: center">
            <image @tap.stop="likePost()" class="btn-img" :src="!post.isLiked ? 'https://www.douluodalu.icu:9000/school/static/like.png' : 'https://www.douluodalu.icu:9000/school/static/like_active.png'"></image>
            <text>&nbsp;{{ checkParam(post.likes) }}</text>
          </view>
        </view>
      </view>
      <u-gap height="4" bgColor="rgb(247,247,247)"></u-gap>
      <view @tap.stop="toPostByChannel"  class="topic-wrapper">
        <view style="display: flex;align-items: center;">
          <image class="channel-image" lazy-load  :src="channel.url"></image>
          &nbsp;&nbsp;<view style="display: flex;flex-direction: column">
          <text class="channel-name">#&nbsp;{{channel.name}}</text>
          <text style="color: rgb(162,162,162);font-size: 12px">9999&nbsp;{{channel.nickname}}</text>
        </view>
        </view>
        <view  style="color: black;font-weight: bold ;display: flex;align-items: center">
          <text>进入&nbsp;</text>
          <text>⇁</text>
        </view>
      </view>
      <u-gap height="3" bgColor="rgb(247,247,247)"></u-gap>
    </view>
  </view>

</template>
<script>

import {likePost} from "@/api/post";
import {getToken, getUserId} from "@/utils/auth";
import {followUser} from "@/api/user";

export default {
  props: ['post','channel'],
  data() {
    return {

      channelInfo:{},
      videoContext: null,
      publishTime: null,
      fileList: [],
      commentIndex: 0,

      current: 0,
      baseList: [{
        name: 'photo',
        title: '图片'
      },
        {
          name: 'lock',
          title: '锁头'
        },
        {
          name: 'star',
          title: '星星'
        },
      ],
      tagStyle: {
        p: 'color: #000; line-height: 24px;'
      },
      shadowStyle: {
        backgroundImage: "none",
        paddingTop: "0",
        marginTop: "20rpx"
      },
      content: `<p>浔阳江头夜送客，枫叶荻花秋瑟瑟。主人下马客在船，举酒欲饮无管弦。醉不成欢惨将别，别时茫茫江浸月。
					忽闻水上琵琶声，主人忘归客不发。寻声暗问弹者谁，琵琶声停欲语迟。移船相近邀相见，添酒回灯重开宴。千呼万唤始出来，犹抱琵琶半遮面。转轴拨弦三两声，未成曲调先有情。弦弦掩抑声声思，似诉平生不得志。低眉信手续续弹，说尽心中无限事。轻拢慢捻抹复挑，初为《霓裳》后《六幺》。大弦嘈嘈如急雨，小弦切切如私语。嘈嘈切切错杂弹，大珠小珠落玉盘。间关莺语花底滑，幽咽泉流冰下难。冰泉冷涩弦凝绝，凝绝不通声暂歇。别有幽愁暗恨生，此时无声胜有声。银瓶乍破水浆迸，铁骑突出刀枪鸣。曲终收拨当心画，四弦一声如裂帛。东船西舫悄无言，唯见江心秋月白。
					沉吟放拨插弦中，整顿衣裳起敛容。自言本是京城女，家在虾蟆陵下住。十三学得琵琶成，名属教坊第一部。曲罢曾教善才服，妆成每被秋娘妒。五陵年少争缠头，一曲红绡不知数。钿头银篦击节碎，血色罗裙翻酒污。今年欢笑复明年，秋月春风等闲度。弟走从军阿姨死，暮去朝来颜色故。门前冷落鞍马稀，老大嫁作商人妇。商人重利轻别离，前月浮梁买茶去。去来江口守空船，绕船月明江水寒。夜深忽梦少年事，梦啼妆泪红阑干。
					我闻琵琶已叹息，又闻此语重唧唧。同是天涯沦落人，相逢何必曾相识！我从去年辞帝京，谪居卧病浔阳城。浔阳地僻无音乐，终岁不闻丝竹声。住近湓江地低湿，黄芦苦竹绕宅生。其间旦暮闻何物？杜鹃啼血猿哀鸣。春江花朝秋月夜，往往取酒还独倾。岂无山歌与村笛？呕哑嘲哳难为听。今夜闻君琵琶语，如听仙乐耳暂明。莫辞更坐弹一曲，为君翻作《琵琶行》。感我此言良久立，却坐促弦弦转急。凄凄不似向前声，满座重闻皆掩泣。座中泣下谁最多？江州司马青衫湿。</p>`,
      showHeight: 200,
      scrollTop: 0,
      old: {
        scrollTop: 0
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        authorName: null,
        channelId: null,
        labels: null,
        countyId: null,
        createdTime: null,
        publishTime: null,
        origin: null,
      },
      myUserId:'',
    }
  },
  mounted() {

    this.myUserId = getUserId()
    if (this.post.videos != null) {
      let videoList = this.post.videos.split(',');
      this.fileList = [...this.fileList, ...videoList]
    }
    if (this.post.images != null) {
      let imageList = this.post.images.split(',');
      this.fileList = [...this.fileList, ...imageList]
    }
  },
  created() {
  },
  methods: {
    async followUser() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if(this.post?.isFollowed){
        uni.showModal({
          content: '确定要取消关注吗？',
          success: async (res) => {
            if (res.confirm) {
              const res = await followUser(this.post?.authorId,false)
              if(res.code == 200){
                this.post.isFollowed = false
                uni.showToast({title: '取消关注成功',icon: 'none'})
              }
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        })
      }else {
        const res = await followUser(this.post?.authorId,true)
        if(res.code == 200){
          this.post.isFollowed  = true
          uni.showToast({title: '关注成功',icon: 'none'})
        }
      }
    },
    async likePost(){
            let token = getToken();
      if(!(token !== null && token !== ''&& token !== undefined)){
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      const res =  await likePost(this.post.id)
      this.post.isLiked ? this.post.likes-- : this.post.likes++
      this.post.isLiked = !this.post.isLiked
      console.log(res)
    },
    sendFileList(currentIndex) {
      setTimeout(() => {
        uni.$emit('sendFileList', {
          post: this.post,
          fileList: this.fileList,
          currentIndex: currentIndex
        })
        console.log("发送")
      }, 500)

    },

    isImageUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tif', '.tiff'];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return imageExtensions.includes(extension) && url.startsWith("http");
    },
    isVideoUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      let videoExtensions = [".3gp", ".avi", ".flv", ".mkv", ".mov", ".mpg", ".mp4", ".rmvb", ".wmv"];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return videoExtensions.includes(extension) && url.startsWith("http");
    },
    toPostByChannel(){
      uni.navigateTo({
        url: '/pages/topic/topicByChannel?id=' + this.post.channelId
      })
    },
    toUserInfo(){
      uni.navigateTo({
        url: '/pages/my/userInfo?id=' + this.post.authorId
      })
    },
    checkParam(value) {
      if (value === '' || value === undefined || value === null) {
        if (typeof value === 'number') {
          return 0;
        }
        if (typeof value === 'string') {
          return '无';
        }
      } else {
        return value;
      }
    },
    click(name) {
      this.$refs.uToast.success(`点击了第${name}个`)
    },
    load() {
      this.$refs.uReadMore.init();
    }
  }
}
</script>
<style>
.btn-wrapper {
  padding: 5px 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border: none;
  outline: none;
}

.btn-img {
  font-weight: bolder;
  font-size: 14px;
  color: black;
  height: 20px;
  width: 20px;
}

.topic-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 3rem;
  padding: 10px 15px;

}
.channel-image{
  width: 3rem;
  height: 3rem;
  border: none;
  border-radius: 15px;
}
.channel-name{
  font-weight: bolder;
  color: black;
  font-size: 14px;
}

.topic {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bolder;
  padding: 2px;
  width: 15px;
  height: 15px;
  color: white;
  border-radius: 50%;
  background-color: #4ea4f9
}

.image-wrapper {
  padding: 4px 0;
}

.top {
  display: flex;
  align-items: center;
//width: 100%; justify-content: space-between; padding: 5px 13px;
}

.custom-style {
  background-color: #FFFFFF;
  border: none;
  font-weight: bold;
  font-size: 14px;
  border-radius: 72rpx;
  padding: 2px 8px;
  color: #4ea4f9;
  margin-right: 34px;
}
.custom-style-followed {
  background-color: white;
  border: none;
  font-weight: bold;
  font-size: 14px;
  border-radius: 72rpx;
  padding: 2px 8px;
  color: rgba(114, 118, 123, 0.38);
  margin-right: 34px;
}

.content {
  padding: 0 15px;
  margin: 0;
}

.top-left {
  display: flex;
  align-items: center;
}

.nick-name {
  font-size: 20rpx;
  color: #555555;
  font-style: initial;
  padding-left: 20rpx;
}

.avatar {
  border-radius: 50%;
  height: 80rpx;
  width: 80rpx;
}

.blog-wrapper {
  border-bottom: 3px solid #f0f0f0;
  width: 100%;
  height: auto;
}

image {
  will-change: transform
}

.file-item-multi {
  margin-bottom: 0.5rem;
  border-radius: 10px;
  width: 7.5rem;
  height: 7.5rem;
  position: relative;
}

.file-item-multi-1-row {
  border-radius: 5px;
  width: 7.5rem;
  height: 7.5rem;
}

.file-item-multi-1-col {
  margin-bottom: 5px;
  border-radius: 5px;
  width: 7.5rem;
  height: 7.5rem;
}

.file-item-multi-4 {
  border-radius: 5px;
  width: 7.5rem;
  height: 7.5rem;
}

.play-btn {
  width: 40px;
  height: 40px;
  top: 30%;
  left: 30%;
  position: absolute
}
</style>
